<?php

require_once 'Zend/Controller/Action.php';

class St_Controller_Action extends Zend_Controller_Action {

    public $baseUrl = "";
    public $layoutUrl = "";
    public $externalUrl = "";
    protected $session = "";
    protected $auth = null;
    protected $logger = null;

    public function init() {
        $modelDir = $this->getFrontController()->getModuleDirectory()
                . DIRECTORY_SEPARATOR . 'models';
        set_include_path(implode(PATH_SEPARATOR, array(
                    $modelDir,
                    get_include_path(),
                )));

        $this->view->baseUrl = $this->_getBaseUrl();
        $this->view->layoutUrl = $this->_getLayoutUrl();
        $this->view->externalUrl = $this->_getExternalUrl();

        Zend_Loader::loadClass("Zend_Session_Namespace");

        if (isset($_POST['user']) && isset($_POST['user']['rememberme'])) {
            Zend_Session::setOptions(
                    array(
                        'remember_me_seconds' => 864000 * 30,
                        'use_only_cookies' => 'on'
                    )
            );
            Zend_Session::rememberMe(84000 * 30);
        }

        Zend_Loader::loadClass("Zend_Session_Namespace");

        $this->session = new Zend_Session_Namespace(St_Registry::getConfig("appnamespace"));
        St_Registry::set('session', $this->session);

        Zend_Loader::loadClass("St_Auth");
        Zend_Loader::loadClass("St_Auth_Storage");

        $this->auth = St_Auth::getInstance();
        $authStorage = new St_Auth_Storage();
        $this->auth->setStorage($authStorage);
        St_Registry::set('auth', $this->auth);

        if ($this->auth->isLogin()) {
            $currentUser = $this->_getCurrentUser();
            if (!$currentUser) {
                $this->auth->clearAuthInfo();
                $this->_redirect("access");
            }
            $this->view->user = $currentUser;
        }

        $baseUrl = St_Registry::getConfig("base_url");
        $this->view->rootBaseUrl = $baseUrl;

        $translator = St_Registry::get("translator");

        $defaultLanguageCode = St_Registry::getConfig("default_language_code");
        if (!$defaultLanguageCode) {
            $defaultLanguageCode = "en";
        }
        $translator->setLocale($defaultLanguageCode);
        if ($this->session->languageCode) {
            $translator->setLocale($this->session->languageCode);
        }
        $this->view->translate = $translator;

        // initialize log
        Zend_Loader::loadClass("St_Log");

        $logColumnMapping = array(
            'DateTime' => 'DateTime',
            'IPAddress' => 'IPAddress',
            'TransactionText' => 'TransactionText',
            'UserID' => 'UserID'
        );

        $db = St_Registry::getDB();
        $dbPrefix = St_Registry::getDBPrefix();

        $writer = new Zend_Log_Writer_Db($db, $dbPrefix . 'transaction_log', $logColumnMapping);
        $this->logger = new St_Log($writer);
        if ($this->auth->isLogin()) {
            $this->logger->setUserId($currentUser['UserID']);
        }
        // End of log set up
    }

    private function _setLanguage($languageCode) {
        $translator = St_Registry::get("translator");
        $translator->setLocale($languageCode);
    }

    private function _getLanguageCode() {
        $defaultLanguageCode = St_Registry::getConfig("default_language_code");
        if (!$defaultLanguageCode) {
            $defaultLanguageCode = "en";
        }
        if ($this->session->languageCode) {
            $defaultLanguageCode = $this->session->languageCode;
        }
        return $defaultLanguageCode;
    }

    public function loadModel($class, $module = null) {
        $modelDir = $this->getFrontController()
                        ->getModuleDirectory($module)
                . DIRECTORY_SEPARATOR . 'models';
        Zend_Loader::loadClass($class, $modelDir);
        return $class;
    }

    protected function _getBaseUrl() {
        $this->baseUrl = St_Registry::getConfig("base_url");
        St_Registry::set("BASE_URL", $this->baseUrl);
        return $this->baseUrl;
    }

    protected function _getLayoutUrl() {
        $template = St_Registry::getConfig("template");
        $application = St_Registry::getConfig("appnamespace");
        $baseUrl = St_Registry::getConfig("base_url");
        $this->layoutUrl = "{$baseUrl}application/{$application}/layouts/{$template}/";
        return $this->layoutUrl;
    }

    protected function _getExternalUrl() {
        $this->externalUrl = $this->_getBaseUrl() . "/../application/" . St_Registry::getConfig("appnamespace") . "/externals/";
    }

    protected function _setNoViewRender($value = true) {
        $this->_helper->viewRenderer->setNoRender($value);
    }

    protected function _loadMenu($menuName = "default") {
        $menuResource = include APPLICATION_PATH . '/configs/menu.php';
        if (!isset($menuResource[$menuName])) {
            $menuName = 'default';
        }
        $navigation = new Zend_Navigation($menuResource[$menuName]);
        return $navigation;
    }

    protected function _getMenuNameList() {
        $menuResource = include APPLICATION_PATH . '/configs/menu.php';
        $arrData = array();
        foreach ($menuResource as $k => $v) {
            $arrData[] = $k;
        }
        return $arrData;
    }

    protected function _getFilterPostQuote($data) {
        if (get_magic_quotes_gpc()) {
            return stripslashes($data);
        }
        return $data;
    }

    protected function _getCurrentUser() {
        if (St_Registry::isRegistered('user_data')) {
            return St_Registry::get('user_data');
        }

        if (!$this->auth->isLogin()) {
            return false;
        } else {
            $username = $this->auth->getUsername();
            $db = St_Registry::getDB();

            $selectUser = $db->select()->from('user')->where("email = '{$username}'");
            $select = $db->select()
                    ->from(array('u' => $selectUser))
                    ->joinLeft(array('g' => 'group'), 'u.GroupID = g.GroupID', array('GroupName' => 'GroupName', 'GroupMenu' => 'GroupMenu'));
            $user = $db->fetchRow($select);
            St_Registry::set('user_data', $user);
            return $user;
        }
    }

    // list or group
    protected function _getPermissionData($node = "list") {
        $permissionResource = include APPLICATION_PATH . '/configs/permission.php';
        return $permissionResource["permission_" . $node];
    }

    protected function _getSuperAdminGroupID() {
        $groupListSetting = $this->_getPermissionData("group");
        return $groupListSetting["superadmin_group_id"];
    }

    protected function isSuperAdmin() {
        $user = $this->_getCurrentUser();
        $groupListSetting = $this->_getPermissionData("group");
        if ($user['GroupID'] == $groupListSetting["superadmin_group_id"]) {
            return true;
        }
        return false;
    }

}